import { updateVnote } from "./react-dom";

export const updateQueue = {
    isBatchData: false, // 标识是同步更新还是异步更新
    updaters: [],

    batchUpdate() {
        updateQueue.updaters.forEach((updater) => {
            updater.updateComponent();
        });
        updateQueue.isBatchData = false;
        updateQueue.updaters = [];
    },
};

class Updater {
    constructor(classInstance) {
        this.classInstance = classInstance;
        this.paddingState = [];
    }

    // 添加待更新的state
    addState(partialState) {
        this.paddingState.push(partialState);
        this.emitUpdate();
    }

    emitUpdate() {
        // 判断是异步还是同步更新
        if (updateQueue.isBatchData) {
            //异步更新
            //需要收集setState
            updateQueue.updaters.push(this);
            return;
        }

        // 同步更新
        this.updateComponent();
    }

    updateComponent() {
        let { paddingState, classInstance } = this;
        if (paddingState.length > 0) {
            shouldUpdate(classInstance, this.getState());
        }
    }

    // 获取最新的state
    getState() {
        let { paddingState, classInstance } = this;
        let { state } = classInstance;
        paddingState.forEach((newState) => {
            state = { ...state, ...newState };
        });
        paddingState.length = 0;
        return state;
    }
}

// React 组件更新
function shouldUpdate(classInstance, newState) {
    classInstance.state = newState;
    classInstance.forceUpdate();
}

class Component {
    static isReactComponent = true;

    constructor(props) {
        this.props = props;
        this.state = {};
        this.updater = new Updater(this);
    }

    setState(partialState) {
        this.updater.addState(partialState);
    }

    forceUpdate() {
        let newVnode = this.render();
        let oldVnode = this.oldReaderVnode;
        let oldDom = oldVnode.dom;
        updateVnote(oldDom.parentNode, oldVnode, newVnode);
        this.oldReaderVnode = newVnode;
    }
}

export default Component;
